/*
 * Copyright (C) 2004-2014 L2J Server
 * 
 * This file is part of L2J Server.
 * 
 * L2J Server is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * L2J Server is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.l2jserver.gameserver.model.entity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
//import java.net.URL;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.l2jserver.Config;
import com.l2jserver.gameserver.Announcements;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;

/**
 * @author Kyrell
 * @version 3.0
 */
public class AutoVoteRewardHandler
{
	protected static final Logger _log = Logger.getLogger(AutoVoteRewardHandler.class.getName());
	// URL from your server site at HopZone.net
	// Example: http://l2.hopzone.net/lineage2/moreinfo ... er/ID.html
	// private final static String _url = "http://l2.hopzone.net/lineage2/details/93806/L2EndlessWorld"; //Add your URL from HopZone here!
	// private final static String_url = "http://l2.hopzone.net/lineage2/moreinfo/L2EndlessWorld/93806.html";
	// Reward all online players each '_votesRequiredForReward' votes.
	private final int _votesRequiredForReward = Config.NEEDVOTES;//
	// Initial check, time in minutes:
	// Default: 1 minute
	private final int initialCheck = Config.FIRSTCHECK;
	// Delay interval, time in minutes (do not set it too low):
	// Default: 10 minutes
	private final int delayForCheck = Config.EVERYCHECK;
	
	// Item Id, Amount.
	private final static int[][] ITEMs =
	{
		{
			22742,
			4
		}, // Coin of Luck (Event)
		
	};
	
	// Do not change
	private int _lastVoteCount = 0;
	
	@SuppressWarnings("synthetic-access")
	private AutoVoteRewardHandler()
	{
		_log.info("[AutoVoteRewardHandler]: Vote Reward System Initiated.");
		ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new AutoReward(), initialCheck * 60000, delayForCheck * 60000);
	}
	
	private class AutoReward implements Runnable
	{
		@Override
		@SuppressWarnings("synthetic-access")
		public void run()
		{
			int votes = getVotes() + getVotesTZ();
			int rewardedPlayers = 0;
			if (votes > -1)
			{
				if ((getLastVoteCount() != 0) && (votes >= (getLastVoteCount() + _votesRequiredForReward)))
				{
					Collection<L2PcInstance> players = L2World.getInstance().getPlayers();
					for (L2PcInstance player : players)
					{
						if ((player != null) && !player.getClient().isDetached())
						{
							for (int[] reward : ITEMs)
							{
								if (player.getInventory().validateCapacityByItemId(reward[0]))
								{
									player.addItem("reward", reward[0], reward[1], player, true);
									
								}
							}
							rewardedPlayers++;
						}
					}
					setLastVoteCount(getLastVoteCount() + _votesRequiredForReward);
				}
				else if (getLastVoteCount() == 0)
				{
					setLastVoteCount(votes);
				}
				
				_log.info("[AutoVoteRewardHandler]: Server Votes: " + votes + ", Rewarded players: " + rewardedPlayers);
				Announcements.getInstance().announceToAll("Server Votes: " + votes + " | Next Reward on " + (getLastVoteCount() + _votesRequiredForReward) + " votes!");
			}
			else
			{
				_log.log(Level.WARNING, "[AutoVoteRewardHandler]: Error retreiving server votes count!");
			}
		}
	}
	
	private static int getVotes()
	{
		final String HOPZONE = Config.HOPZONE;
		URL url = null;
		URLConnection con = null;
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader in = null;
		int votes = -1;
		try
		{
			// in = new BufferedReader(new InputStreamReader(new URL(_url).openStream()));
			url = new URL(HOPZONE);
			con = url.openConnection();
			con.addRequestProperty("User-Agent", "Mozilla/4.76");
			is = con.getInputStream();
			isr = new InputStreamReader(is);
			in = new BufferedReader(isr);
			String inputLine;
			while (((inputLine = in.readLine()) != null) && (votes == -1))
			{
				// for hopzone
				if (inputLine.contains("rank anonymous tooltip"))
				{
					votes = Integer.valueOf(inputLine.split(">")[2].replace("</span", ""));
					break;
				}
				
			}
			in.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "[AutoVoteRewardHandler]: " + e.getMessage(), e);
		}
		return votes;
	}
	
	private static int getVotesTZ()
	{
		final String TOPZONE = Config.TOPZONE;
		URL urlTZ = null;
		URLConnection conTZ = null;
		InputStream isTZ = null;
		InputStreamReader isrTZ = null;
		BufferedReader inTZ = null;
		int votes = -1;
		try
		{
			// in = new BufferedReader(new InputStreamReader(new URL(_url).openStream()));
			urlTZ = new URL(TOPZONE);
			conTZ = urlTZ.openConnection();
			conTZ.addRequestProperty("User-Agent", "Mozilla/4.76");
			isTZ = conTZ.getInputStream();
			isrTZ = new InputStreamReader(isTZ);
			inTZ = new BufferedReader(isrTZ);
			String inputLine;
			while (((inputLine = inTZ.readLine()) != null) && (votes == -1))
			{
				// for topzone
				if (inputLine.contains("Votes"))
				{
					votes = Integer.valueOf(inputLine.split(">")[3].replace("</div", ""));
					break;
				}
				
			}
			inTZ.close();
		}
		catch (Exception e)
		{
			_log.log(Level.WARNING, "[AutoVoteRewardHandler]: " + e.getMessage(), e);
		}
		return votes;
	}
	
	private void setLastVoteCount(int voteCount)
	{
		_lastVoteCount = voteCount;
	}
	
	private int getLastVoteCount()
	{
		return _lastVoteCount;
	}
	
	public static AutoVoteRewardHandler getInstance()
	{
		return SingletonHolder._instance;
	}
	
	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder
	{
		protected static final AutoVoteRewardHandler _instance = new AutoVoteRewardHandler();
	}
	
	public static void main(String[] args)
	{
		int anzahl;
		anzahl = getVotesTZ() + getVotes();
		System.out.println("Server votes: " + anzahl);// Just a test.
		AutoVoteRewardHandler.getInstance();
	}
}